package job

import (
	"github.com/jinzhu/gorm"
	"time"
)

func GetOrCreateJobInTx(db *gorm.DB, name string) (*Job, error) {
	job, err := getJob(db, name, true)
	if err == nil {
		return job, nil
	}

	if err != gorm.ErrRecordNotFound {
		return job, err
	}

	job = &Job{
		Name:       name,
		LastRun:    time.Now(),
		LastStatus: JobRunNone,
		RunCount:   0,
	}
	err = db.Create(job).Error
	if err != nil {
		return nil, err
	}
	return job, nil
}

func getJob(db *gorm.DB, name string, lock bool) (*Job, error) {
	job := Job{}
	if lock {
		db = db.Set("gorm:query_option", "FOR UPDATE NOWAIT")
	}
	err := db.First(&job, "name = ?", name).Error
	return &job, err
}

func UpdateJob(db *gorm.DB, jobId int64, runAt time.Time, status string) (int64, error) {
	_db := db.Model(&Job{}).Where("id=?", jobId).
		Updates(map[string]interface{}{
			"last_run":    runAt,
			"last_status": status,
			"run_count":   gorm.Expr("run_count + 1"),
			"updated_at":  time.Now(),
		})
	return _db.RowsAffected, _db.Error
}

func AddJobHist(db *gorm.DB, record *JobHist) error {
	return db.Create(record).Error
}

func UpdateJobHist(db *gorm.DB, record *JobHist) error {
	return db.Save(record).Error
}
